using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Authorization;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using Volo.Abp.Identity;
using Volo.Abp.Localization;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Users;
using CKY.AgentPlatform.Localization;

namespace CKY.AgentPlatform.Authorization
{
    /// <summary>
    /// 平台权限定义
    /// </summary>
    public static class AgentPlatformPermissions
    {
        public const string GroupName = "AgentPlatform";

        // 智能体管理权限
        public static class Agents
        {
            public const string Default = GroupName + ".Agents";
            public const string Create = Default + ".Create";
            public const string Update = Default + ".Update";
            public const string Delete = Default + ".Delete";
            public const string Manage = Default + ".Manage";
            public const string View = Default + ".View";
        }

        // 模型配置权限
        public static class ModelConfigs
        {
            public const string Default = GroupName + ".ModelConfigs";
            public const string Create = Default + ".Create";
            public const string Update = Default + ".Update";
            public const string Delete = Default + ".Delete";
            public const string Manage = Default + ".Manage";
            public const string View = Default + ".View";
        }

        // 提示词模板权限
        public static class PromptTemplates
        {
            public const string Default = GroupName + ".PromptTemplates";
            public const string Create = Default + ".Create";
            public const string Update = Default + ".Update";
            public const string Delete = Default + ".Delete";
            public const string Manage = Default + ".Manage";
            public const string View = Default + ".View";
        }

        // MCP工具权限
        public static class McpTools
        {
            public const string Default = GroupName + ".McpTools";
            public const string Create = Default + ".Create";
            public const string Update = Default + ".Update";
            public const string Delete = Default + ".Delete";
            public const string Manage = Default + ".Manage";
            public const string View = Default + ".View";
            public const string Execute = Default + ".Execute";
        }

        // MCP服务器权限
        public static class McpServers
        {
            public const string Default = GroupName + ".McpServers";
            public const string Create = Default + ".Create";
            public const string Update = Default + ".Update";
            public const string Delete = Default + ".Delete";
            public const string Manage = Default + ".Manage";
            public const string View = Default + ".View";
            public const string Connect = Default + ".Connect";
            public const string Test = Default + ".Test";
        }

        // 对话管理权限
        public static class Conversations
        {
            public const string Default = GroupName + ".Conversations";
            public const string Create = Default + ".Create";
            public const string Update = Default + ".Update";
            public const string Delete = Default + ".Delete";
            public const string Manage = Default + ".Manage";
            public const string View = Default + ".View";
            public const string Export = Default + ".Export";
        }

        // 性能监控权限
        public static class Performance
        {
            public const string Default = GroupName + ".Performance";
            public const string View = Default + ".View";
            public const string Manage = Default + ".Manage";
            public const string Monitor = Default + ".Monitor";
            public const string Optimize = Default + ".Optimize";
        }

        // 统计分析权限
        public static class Statistics
        {
            public const string Default = GroupName + ".Statistics";
            public const string View = Default + ".View";
            public const string Export = Default + ".Export";
            public const string Manage = Default + ".Manage";
        }

        // 系统管理权限
        public static class System
        {
            public const string Default = GroupName + ".System";
            public const string Manage = Default + ".Manage";
            public const string Settings = Default + ".Settings";
            public const string Logs = Default + ".Logs";
            public const string Monitor = Default + ".Monitor";
        }

        // 用户权限
        public static class Users
        {
            public const string Default = GroupName + ".Users";
            public const string Manage = Default + ".Manage";
            public const string View = Default + ".View";
            public const string Create = Default + ".Create";
            public const string Update = Default + ".Update";
            public const string Delete = Default + ".Delete";
        }
    }

    /// <summary>
    /// 权限提供者
    /// </summary>
    public class AgentPlatformPermissionDefinitionProvider : PermissionDefinitionProvider
    {
        public override void Define(IPermissionDefinitionContext context)
        {
            var agentPlatformGroup = context.AddGroup(AgentPlatformPermissions.GroupName, LocalizableString.Create<AgentPlatformResource>("AgentPlatform"));

            // 智能体管理权限
            var agentsPermission = agentPlatformGroup.AddPermission(AgentPlatformPermissions.Agents.Default, LocalizableString.Create<AgentPlatformResource>("Permission:Agents"));
            agentsPermission.AddChild(AgentPlatformPermissions.Agents.View, LocalizableString.Create<AgentPlatformResource>("Permission:Agents.View"));
            agentsPermission.AddChild(AgentPlatformPermissions.Agents.Create, LocalizableString.Create<AgentPlatformResource>("Permission:Agents.Create"));
            agentsPermission.AddChild(AgentPlatformPermissions.Agents.Update, LocalizableString.Create<AgentPlatformResource>("Permission:Agents.Update"));
            agentsPermission.AddChild(AgentPlatformPermissions.Agents.Delete, LocalizableString.Create<AgentPlatformResource>("Permission:Agents.Delete"));
            agentsPermission.AddChild(AgentPlatformPermissions.Agents.Manage, LocalizableString.Create<AgentPlatformResource>("Permission:Agents.Manage"));

            // 模型配置权限
            var modelConfigsPermission = agentPlatformGroup.AddPermission(AgentPlatformPermissions.ModelConfigs.Default, LocalizableString.Create<AgentPlatformResource>("Permission:ModelConfigs"));
            modelConfigsPermission.AddChild(AgentPlatformPermissions.ModelConfigs.View, LocalizableString.Create<AgentPlatformResource>("Permission:ModelConfigs.View"));
            modelConfigsPermission.AddChild(AgentPlatformPermissions.ModelConfigs.Create, LocalizableString.Create<AgentPlatformResource>("Permission:ModelConfigs.Create"));
            modelConfigsPermission.AddChild(AgentPlatformPermissions.ModelConfigs.Update, LocalizableString.Create<AgentPlatformResource>("Permission:ModelConfigs.Update"));
            modelConfigsPermission.AddChild(AgentPlatformPermissions.ModelConfigs.Delete, LocalizableString.Create<AgentPlatformResource>("Permission:ModelConfigs.Delete"));
            modelConfigsPermission.AddChild(AgentPlatformPermissions.ModelConfigs.Manage, LocalizableString.Create<AgentPlatformResource>("Permission:ModelConfigs.Manage"));

            // 提示词模板权限
            var promptTemplatesPermission = agentPlatformGroup.AddPermission(AgentPlatformPermissions.PromptTemplates.Default, LocalizableString.Create<AgentPlatformResource>("Permission:PromptTemplates"));
            promptTemplatesPermission.AddChild(AgentPlatformPermissions.PromptTemplates.View, LocalizableString.Create<AgentPlatformResource>("Permission:PromptTemplates.View"));
            promptTemplatesPermission.AddChild(AgentPlatformPermissions.PromptTemplates.Create, LocalizableString.Create<AgentPlatformResource>("Permission:PromptTemplates.Create"));
            promptTemplatesPermission.AddChild(AgentPlatformPermissions.PromptTemplates.Update, LocalizableString.Create<AgentPlatformResource>("Permission:PromptTemplates.Update"));
            promptTemplatesPermission.AddChild(AgentPlatformPermissions.PromptTemplates.Delete, LocalizableString.Create<AgentPlatformResource>("Permission:PromptTemplates.Delete"));
            promptTemplatesPermission.AddChild(AgentPlatformPermissions.PromptTemplates.Manage, LocalizableString.Create<AgentPlatformResource>("Permission:PromptTemplates.Manage"));

            // MCP工具权限
            var mcpToolsPermission = agentPlatformGroup.AddPermission(AgentPlatformPermissions.McpTools.Default, LocalizableString.Create<AgentPlatformResource>("Permission:McpTools"));
            mcpToolsPermission.AddChild(AgentPlatformPermissions.McpTools.View, LocalizableString.Create<AgentPlatformResource>("Permission:McpTools.View"));
            mcpToolsPermission.AddChild(AgentPlatformPermissions.McpTools.Create, LocalizableString.Create<AgentPlatformResource>("Permission:McpTools.Create"));
            mcpToolsPermission.AddChild(AgentPlatformPermissions.McpTools.Update, LocalizableString.Create<AgentPlatformResource>("Permission:McpTools.Update"));
            mcpToolsPermission.AddChild(AgentPlatformPermissions.McpTools.Delete, LocalizableString.Create<AgentPlatformResource>("Permission:McpTools.Delete"));
            mcpToolsPermission.AddChild(AgentPlatformPermissions.McpTools.Manage, LocalizableString.Create<AgentPlatformResource>("Permission:McpTools.Manage"));
            mcpToolsPermission.AddChild(AgentPlatformPermissions.McpTools.Execute, LocalizableString.Create<AgentPlatformResource>("Permission:McpTools.Execute"));

            // MCP服务器权限
            var mcpServersPermission = agentPlatformGroup.AddPermission(AgentPlatformPermissions.McpServers.Default, LocalizableString.Create<AgentPlatformResource>("Permission:McpServers"));
            mcpServersPermission.AddChild(AgentPlatformPermissions.McpServers.View, LocalizableString.Create<AgentPlatformResource>("Permission:McpServers.View"));
            mcpServersPermission.AddChild(AgentPlatformPermissions.McpServers.Create, LocalizableString.Create<AgentPlatformResource>("Permission:McpServers.Create"));
            mcpServersPermission.AddChild(AgentPlatformPermissions.McpServers.Update, LocalizableString.Create<AgentPlatformResource>("Permission:McpServers.Update"));
            mcpServersPermission.AddChild(AgentPlatformPermissions.McpServers.Delete, LocalizableString.Create<AgentPlatformResource>("Permission:McpServers.Delete"));
            mcpServersPermission.AddChild(AgentPlatformPermissions.McpServers.Manage, LocalizableString.Create<AgentPlatformResource>("Permission:McpServers.Manage"));
            mcpServersPermission.AddChild(AgentPlatformPermissions.McpServers.Connect, LocalizableString.Create<AgentPlatformResource>("Permission:McpServers.Connect"));
            mcpServersPermission.AddChild(AgentPlatformPermissions.McpServers.Test, LocalizableString.Create<AgentPlatformResource>("Permission:McpServers.Test"));

            // 对话管理权限
            var conversationsPermission = agentPlatformGroup.AddPermission(AgentPlatformPermissions.Conversations.Default, LocalizableString.Create<AgentPlatformResource>("Permission:Conversations"));
            conversationsPermission.AddChild(AgentPlatformPermissions.Conversations.View, LocalizableString.Create<AgentPlatformResource>("Permission:Conversations.View"));
            conversationsPermission.AddChild(AgentPlatformPermissions.Conversations.Create, LocalizableString.Create<AgentPlatformResource>("Permission:Conversations.Create"));
            conversationsPermission.AddChild(AgentPlatformPermissions.Conversations.Update, LocalizableString.Create<AgentPlatformResource>("Permission:Conversations.Update"));
            conversationsPermission.AddChild(AgentPlatformPermissions.Conversations.Delete, LocalizableString.Create<AgentPlatformResource>("Permission:Conversations.Delete"));
            conversationsPermission.AddChild(AgentPlatformPermissions.Conversations.Manage, LocalizableString.Create<AgentPlatformResource>("Permission:Conversations.Manage"));
            conversationsPermission.AddChild(AgentPlatformPermissions.Conversations.Export, LocalizableString.Create<AgentPlatformResource>("Permission:Conversations.Export"));

            // 性能监控权限
            var performancePermission = agentPlatformGroup.AddPermission(AgentPlatformPermissions.Performance.Default, LocalizableString.Create<AgentPlatformResource>("Permission:Performance"));
            performancePermission.AddChild(AgentPlatformPermissions.Performance.View, LocalizableString.Create<AgentPlatformResource>("Permission:Performance.View"));
            performancePermission.AddChild(AgentPlatformPermissions.Performance.Manage, LocalizableString.Create<AgentPlatformResource>("Permission:Performance.Manage"));
            performancePermission.AddChild(AgentPlatformPermissions.Performance.Monitor, LocalizableString.Create<AgentPlatformResource>("Permission:Performance.Monitor"));
            performancePermission.AddChild(AgentPlatformPermissions.Performance.Optimize, LocalizableString.Create<AgentPlatformResource>("Permission:Performance.Optimize"));

            // 统计分析权限
            var statisticsPermission = agentPlatformGroup.AddPermission(AgentPlatformPermissions.Statistics.Default, LocalizableString.Create<AgentPlatformResource>("Permission:Statistics"));
            statisticsPermission.AddChild(AgentPlatformPermissions.Statistics.View, LocalizableString.Create<AgentPlatformResource>("Permission:Statistics.View"));
            statisticsPermission.AddChild(AgentPlatformPermissions.Statistics.Export, LocalizableString.Create<AgentPlatformResource>("Permission:Statistics.Export"));
            statisticsPermission.AddChild(AgentPlatformPermissions.Statistics.Manage, LocalizableString.Create<AgentPlatformResource>("Permission:Statistics.Manage"));

            // 系统管理权限
            var systemPermission = agentPlatformGroup.AddPermission(AgentPlatformPermissions.System.Default, LocalizableString.Create<AgentPlatformResource>("Permission:System"));
            systemPermission.AddChild(AgentPlatformPermissions.System.Manage, LocalizableString.Create<AgentPlatformResource>("Permission:System.Manage"));
            systemPermission.AddChild(AgentPlatformPermissions.System.Settings, LocalizableString.Create<AgentPlatformResource>("Permission:System.Settings"));
            systemPermission.AddChild(AgentPlatformPermissions.System.Logs, LocalizableString.Create<AgentPlatformResource>("Permission:System.Logs"));
            systemPermission.AddChild(AgentPlatformPermissions.System.Monitor, LocalizableString.Create<AgentPlatformResource>("Permission:System.Monitor"));

            // 用户权限
            var usersPermission = agentPlatformGroup.AddPermission(AgentPlatformPermissions.Users.Default, LocalizableString.Create<AgentPlatformResource>("Permission:Users"));
            usersPermission.AddChild(AgentPlatformPermissions.Users.View, LocalizableString.Create<AgentPlatformResource>("Permission:Users.View"));
            usersPermission.AddChild(AgentPlatformPermissions.Users.Create, LocalizableString.Create<AgentPlatformResource>("Permission:Users.Create"));
            usersPermission.AddChild(AgentPlatformPermissions.Users.Update, LocalizableString.Create<AgentPlatformResource>("Permission:Users.Update"));
            usersPermission.AddChild(AgentPlatformPermissions.Users.Delete, LocalizableString.Create<AgentPlatformResource>("Permission:Users.Delete"));
            usersPermission.AddChild(AgentPlatformPermissions.Users.Manage, LocalizableString.Create<AgentPlatformResource>("Permission:Users.Manage"));
        }
    }

    /// <summary>
    /// 权限检查帮助类
    /// </summary>
    public class PermissionCheckerHelper
    {
        private readonly IPermissionChecker _permissionChecker;
        private readonly ICurrentUser _currentUser;

        public PermissionCheckerHelper(
            IPermissionChecker permissionChecker,
            ICurrentUser currentUser)
        {
            _permissionChecker = permissionChecker;
            _currentUser = currentUser;
        }

        /// <summary>
        /// 检查当前用户是否拥有指定权限
        /// </summary>
        public async Task<bool> HasPermissionAsync(string permission)
        {
            return await _permissionChecker.IsGrantedAsync(permission);
        }

        /// <summary>
        /// 检查当前用户是否拥有任意一个权限
        /// </summary>
        public async Task<bool> HasAnyPermissionAsync(params string[] permissions)
        {
            foreach (var permission in permissions)
            {
                if (await _permissionChecker.IsGrantedAsync(permission))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 检查当前用户是否拥有所有权限
        /// </summary>
        public async Task<bool> HasAllPermissionsAsync(params string[] permissions)
        {
            foreach (var permission in permissions)
            {
                if (!await _permissionChecker.IsGrantedAsync(permission))
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 验证权限，如果没有权限则抛出异常
        /// </summary>
        public async Task CheckPermissionAsync(string permission)
        {
            if (!await _permissionChecker.IsGrantedAsync(permission))
            {
                throw new AbpAuthorizationException($"权限不足，需要 {permission} 权限");
            }
        }

        /// <summary>
        /// 验证任意一个权限，如果没有任何权限则抛出异常
        /// </summary>
        public async Task CheckAnyPermissionAsync(params string[] permissions)
        {
            if (!await HasAnyPermissionAsync(permissions))
            {
                throw new AbpAuthorizationException($"权限不足，需要以下权限之一: {string.Join(", ", permissions)}");
            }
        }

        /// <summary>
        /// 验证所有权限，如果缺少任意权限则抛出异常
        /// </summary>
        public async Task CheckAllPermissionsAsync(params string[] permissions)
        {
            if (!await HasAllPermissionsAsync(permissions))
            {
                throw new AbpAuthorizationException($"权限不足，需要以下所有权限: {string.Join(", ", permissions)}");
            }
        }

        /// <summary>
        /// 检查是否为管理员
        /// </summary>
        public bool IsAdmin()
        {
            return _currentUser.IsInRole("admin");
        }

        /// <summary>
        /// 检查是否为系统管理员
        /// </summary>
        public bool IsSystemAdmin()
        {
            return _currentUser.IsInRole("system-admin");
        }

        /// <summary>
        /// 检查是否为当前用户
        /// </summary>
        public bool IsCurrentUser(Guid userId)
        {
            return _currentUser.Id == userId;
        }
    }

    /// <summary>
    /// 权限特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class RequirePermissionAttribute : Attribute
    {
        public string[] Permissions { get; }
        public bool RequireAll { get; set; }

        public RequirePermissionAttribute(string permission, bool requireAll = false)
        {
            Permissions = new[] { permission };
            RequireAll = requireAll;
        }

        public RequirePermissionAttribute(string[] permissions, bool requireAll = false)
        {
            Permissions = permissions;
            RequireAll = requireAll;
        }
    }

    /// <summary>
    /// 角色权限特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class RequireRoleAttribute : Attribute
    {
        public string[] Roles { get; }

        public RequireRoleAttribute(string role)
        {
            Roles = new[] { role };
        }

        public RequireRoleAttribute(string[] roles)
        {
            Roles = roles;
        }
    }
}